<template>
  <div class="border">

    <div class="shopEditHead">
      <el-form :model="details"
               :rules="detailsRules"
               ref="ruleForm"
               label-width="100px"
               class="demo-ruleForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品名称"
                          :rules="{required:true,message: '不能为空'}"
                          prop="goodsName">
              <el-input class="input" v-model="details.goodsName"
                        placeholder="请输入商品名称">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="支持口味"
                          :rules="{required:true,message: '不能为空'}"
                          prop="supportTasteIds">
              <el-select v-model="details.supportTasteIds"
                         @visible-change="visibleChange"
                         style="width:100%"
                         multiple
                         placeholder="请选择">
                <el-option v-for="item in tasteDicList"
                           :key="item.id"
                           :label="item.goodsName"
                           :value="item.id">
                </el-option>
                <el-pagination small
                               layout="prev, pager, next"
                               @current-change="tasteCurrentChange"
                               :page-size="dicSize"
                               :total="tasteDicTotal">
                </el-pagination>
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="款式特点"
                          :rules="{required:true,message: '不能为空'}"
                          prop="styles">

              <el-select v-model="details.styles"
                         @visible-change="visibleStylesChange"
                         style="width:100%"
                         multiple
                         placeholder="请选择">
                <el-option v-for="item in stylesDicList"
                           :key="item.id"
                           :label="item.val"
                           :value="item.id">
                </el-option>
                <el-pagination small
                               layout="prev, pager, next"
                               @current-change="stylesCurrentChange"
                               :page-size="stylesDicSize"
                               :total="stylesDicTotal">
                </el-pagination>
              </el-select>

            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售价"
                          :rules="{required:true,message: '不能为空'}"
                          prop="salePrice">
              <el-input-number class="input"
                               v-model="details.salePrice"
                               :min="0"
                               :precision="0"
                               :controls="false"
                               placeholder="请输入销售价"
                               style="margin-top: 5px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="setLabel">
      <span class="labelItem">
        <span class="textarea">
          <p>商品描述</p>
          <el-input v-model="details.goodsText"
                    type="textarea"
                    :rows="6"
                    :maxlength="1000"
                    show-word-limit
                    placeholder="请输入商品描述"/>
        </span>
      </span>
    </div>



    <!-- 文件上传 -->
    <el-row>
      <el-col :span="8"
              class="padding-right-10">
        <div class="listImgIds">

          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="10"
                     :on-remove="handleRemove"
                     :on-success="handleSuccessUploadFile1"
                     :file-list="lunBoTuFileList"
                     accept=".jpg,.png,.bmp,.jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传商品列表图片</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传10张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="8"
              class="padding-right-10">
        <div class="thumbnailLunbo">
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="10"
                     :on-remove="handleRemove"
                     :on-success="handleSuccessUploadFile2"
                     accept=".jpg,.png,.bmp,.jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传商品详情图片</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传10张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>


<!--      <el-col :span="8"-->
<!--              class="padding-right-10">-->
<!--        <div class="thumbnailLunbo">-->
<!--          &lt;!&ndash; <span class="imguploadtitle">商品轮播图</span> &ndash;&gt;-->
<!--          <el-upload class="upload-demo"-->
<!--                     :headers="{'Authorization': $store.state.app.token}"-->
<!--                     action="/file/uploadFile"-->
<!--                     :limit="10"-->
<!--                     :on-remove="handleRemove"-->
<!--                     :on-success="handleSuccessUploadFile3"-->
<!--                     accept=".jpg,.png,.bmp,.jpeg"-->
<!--                     list-type="picture">-->
<!--            <el-button size="small"-->
<!--                       type="primary">点击上传商品口感图片</el-button>-->
<!--            <div slot="tip"-->
<!--                 class="el-upload__tip">只能上传10张jpg/png文件</div>-->
<!--          </el-upload>-->
<!--        </div>-->
<!--      </el-col>-->

    </el-row>

    <el-row>
      <el-col :span="8"
              class="padding-right-10">
        <div class="thumbnaimian">
          <!-- <span class="imguploadtitle">商品主图</span> -->
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="10"
                     :on-remove="handleRemove"
                     :on-success="handleSuccessUploadFile4"
                     accept=".jpg,.png,.bmp,.jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传商品参数图片</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传10张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="8  "
              class="padding-right-10">
        <div class="thumbnailLunbo">
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="1"
                     :on-remove="handleRemove"
                     :on-success="handleSuccessUploadFile5"
                     accept=".jpg,.png,.bmp,.jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传防伪码图片</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传1张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>

    </el-row>


    <div class="t-right margin-top-10">
      <el-button type="primary"
                 @click="saveAll">提交
      </el-button>
      <el-button type="primary"
                 @click="handleReset">重置
      </el-button>
      <el-button @click="cancelAll">取消</el-button>
    </div>
  </div>
</template>
<script>
import draggable from "vuedraggable";

import {
  addGoods,
  updateGoods,
  deleteGoodsById,
  queryGoodsList,
} from "../../services/goods";

import { getDicList } from '@/services/service_dictionary'



export default {
  name: "YanGanGoodsEditComponent",
  components: {
    draggable
  },
  props: {
    goodsDetails: Object,
  },
  data() {
    return {
      details: {
        goodsId: "",
        tasteNum: "",
        supportTasteIds: "",
        mainImg: "",
        images: [],
        nicotine: "",
        goodsName: "",
        goodsText: "",
        salePrice: "",
        styles: [],

        goodsSpecInfoIds:[],

        listImgIds: "",
        detailImgIds: "",
        tasteImgIds: "",
        paramImgIds: "",
        securityCodeImg: "",

        listImgIdsList:[],
        detailImgIdsList:[],
        tasteImgIdsList:[],
        paramImgIdsList:[],

        isEnable: "1",
      }, // 详情
      detailsRules: {
        nicotine: [
          {required: true, message: '请输入尼古丁含量', trigger: 'blur'},
          {pattern: /^[0-9]\d{0,1}$/, message: '请输入正确数值', trigger: 'blur'}
        ]
      },
      stylesDicList: [],
      tasteDicList: [],

      dicCurrent: 1,
      dicSize: 6,
      tasteDicTotal: 0,

      stylesDicCurrent:1,
      stylesDicSize:6,
      stylesDicTotal: 0,

      //详情表单规则
      tasteList: [
        {
          value: "1",
          label: "槟榔口味",
        },
        {
          value: "2",
          label: "红牛口味",
        }
      ],
      dialogImageUrl: "",
      dialogVisible: false,
      shopDetailsImg: [],

      con: {},
      zhuTuFileList: [],//主图文件列表
      lunBoTuFileList: [],//轮播图文件列表
      shopDetailsImgEnlarge: false, // 详情图放大
      shopDetailsImgEnlargeUrl: "", // 详情图链接
      currentDelBtn: -1,
      currentDelBtnMain: false, // 主图显示删除图片
      currentDelBtndetails: false, // 详情图显示删除图片
      spe: [], // 规格列表
      currentDelBtnListImg: -1,
      linsUpimgSucss: "", // 列表传输成功赋值
      cascaderValue: [], // 商品分类级联值

      benchmarkingProducts: {
        visible: false,
        item: {},
      },
      isSaved: false, // 当前商品是否已保存数据
    };
  },
  computed: {
    control: function () {
      // return this.sr.length / this.specArr[0].spValue.length
      return this.spe.length / this.specArr[0].items.length;
    },


  },

  created() {
    // 判断是否为编辑
    console.log('进来编辑时候 goodsDetail is ',this.goodsDetails)
    if (this.goodsDetails && Object.keys(this.goodsDetails).length > 0) {
      this.details = Object.assign({}, this.details, this.goodsDetails);
      this.changeImgArr(this.details.images, "images");
      const arr = [
        {
          name: "1626677864000",
          url: "https://yiqitong.oss-cn-hangzhou.aliyuncs.com/ALIOSS_IMG/1626677864000"
        },
        {
          name: "16266778640001",
          url: "https://yiqitong.oss-cn-hangzhou.aliyuncs.com/ALIOSS_IMG/16266778640001"
        }
      ]
      this.details.detailImgIdsList=arr;

    }
    // 新增
    else {
      let details = sessionStorage.getItem("goods_add_details");
      if (!details) return;
      this.details = details = JSON.parse(details);
      sessionStorage.removeItem("goods_add_details");
      this.changeImgArr(this.details.images, "images");
    }

  },
  beforeDestroy() {
    console.log("销毁~");
  },


  methods: {
    async queryGoodsList(data) {
      try {
        const res = await queryGoodsList(data);
        if (res.code === 0) {
          this.tasteDicList = res.data.records
          this.tasteDicTotal = res.data.total

        } else {
          this.$message.warning(res.msg)
        }
      } catch (e) {
        console.error(e);
      }
    },

    async getDicList(data) {
      try {
        const res = await getDicList(data);
        const type = data.label;
        if (res.code === 0) {
          this.stylesDicList = res.data.records
          this.stylesDicTotal = res.data.total
        } else {
          this.$message.warning(res.msg)
        }
      } catch (e) {
        console.error(e);
      }
    },

    handleSuccessUploadFile1(file,fileList){
      this.details.listImgIdsList.push(file.data.id);
      this.details.listImgIds =JSON.stringify(this.details.listImgIdsList);
    },
    handleSuccessUploadFile2(file,fileList){
      this.details.detailImgIdsList.push(file.data.id);
      this.details.detailImgIds =JSON.stringify(this.details.detailImgIdsList);

    },
    handleSuccessUploadFile3(file,fileList){
      this.details.tasteImgIdsList.push(file.data.id);
      this.details.tasteImgIds =JSON.stringify(this.details.tasteImgIdsList);
    },
    handleSuccessUploadFile4(file,fileList){
      this.details.paramImgIdsList.push(file.data.id);
      this.details.paramImgIds =JSON.stringify(this.details.paramImgIdsList);
    },
    handleSuccessUploadFile5(file,fileList){
      this.details.securityCodeImg=file.data.id;
    },
    // 处理组件销毁
    handleLeave() {
      this.details.specItems = this.spe || [];
      this.details.specArr = this.specArr || [];
      // 处理详情图数据上传
      this.details.detailImages.map((item, index) => {
        item.sort = this.details.detailImages.length - index;
      });
      this.details.images = this.details.images.map((item) => {
        return item.url;
      });
      this.details.supplierId = "5";
    },

    /**
     * 图片限制
     */
    beforeAvatarUpload(file) {
      const isJPEG = file.name.split(".")[1] === "jpeg";
      const isJPG = file.name.split(".")[1] === "jpg";
      const isPNG = file.name.split(".")[1] === "png";
      const isLt500K = file.size / 1024 / 500 < 2;
      if (!isJPG && !isJPEG && !isPNG) {
        this.$message({
          type: "error",
          message: "上传图片只能是 JPEG/JPG/PNG 格式!",
        });
        return false;
      }
      if (!isLt500K) {
        this.$message({
          type: "error",
          message: "单张图片大小不能超过 500KB!",
        });
        return false;
      }
      console.log((isJPEG || isJPG || isPNG) && isLt500K);
      return (isJPEG || isJPG || isPNG) && isLt500K;
    },
    onMove({relatedContext, draggedContext}) {
      console.log(relatedContext, "relatedContext");
      console.log(draggedContext, "draggedContext");
    },
    change(event) {
      console.log(event, "change");
    },
    start(event) {
      console.log(event, "start");
    },
    end(event) {
      console.log(event, "end");
    },
    changeimglist(file, filelist) {
      console.log(file, "changefile");
      console.log(filelist, "change");
    },

    upimgerror(err, file, fileList) {
      this.$message.error(err);
      console.log(file, "file");
      console.log(fileList, "fileList");
    },

    upImgList(response, file, fileList) {
      console.log(response, "response");
      console.log(file, "file");
      console.log(fileList, "fileList");
    },

    shop_imgList(response, file, fileList) {
      console.log(response, "response");
      console.log(file, "file");
      console.log(fileList, "fileList");
      this.shopDetailsImg = fileList;
    },


    // 轮播图删除回调
    handleRemove(file, fileList) {

    },

    handlePictureCardPreview(file) {
      this.shopDetailsImgEnlargeUrl = file.url;
      this.shopDetailsImgEnlarge = true;
    },

    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 2) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    //  显示删除图片的图标
    showDelBtn(index) {
      this.currentDelBtn = index;
    },

    // 显示删除的图片 主图
    showDelBtnMain() {
      this.currentDelBtnMain = true;
    },

    //  隐藏删除图片 主图
    hiddenDelBtnMain() {
      this.currentDelBtnMain = false;
    },

    // 显示删除列表图
    showDelBtnListImg(index) {
      this.currentDelBtnListImg = index;
    },

    //  隐藏删除列表图
    hiddenDelBtnListImg() {
      this.currentDelBtnListImg = -1;
    },

    // 显示删除的图片 详情图
    showDelBtndetails(index) {
      this.currentDelBtndetails = index;
    },

    //  隐藏删除图片 详情图
    hiddenDelBtndetails() {
      this.currentDelBtndetails = false;
    },

    //  隐藏删除图片的图标
    hiddenDelBtn() {
      this.currentDelBtn = -1;
    },

    // 删除图片
    deleImg(data, index) {
      this.details.images.splice(index, 1);
      this.currentDelBtn = -1;
      console.log(this.details.images, "this.shopDetailsImg");
    },

    // 删除图片 主图
    deleImgMain(d) {
      this.details.mainImg = "";
      this.currentDelBtnMain = false;
    },

    // 删除规格列表图
    deleImgList(d) {
      this.spe[d].img = "";
      this.currentDelBtnListImg = -1;
    },

    // 删除详情图
    deleImgDetails(data, index) {
      this.details.detailImages.splice(index, 1);
      this.currentDelBtndetails = -1;
    },

    // 放大图片
    handlePicture(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },

    // 处理详情图片数组格式
    changeImgArr(a, b) {
      const images = [];
      if (a.length > 0) {
        a.map((item) => {
          const leng = item.split(".jpg")[0].split("/").length - 1;
          item = {
            name: item.split(".jpg")[0].split("/")[leng],
            url: item,
          };
          images.push(item);
        });
        this.$set(this.details, b, images);
      }
    },


    // 保存编辑
    async saveAll() {
      if (this.details.goodsName ==="" || !this.details.goodsName ){
        this.$message.error("商品名称不能为空");
      } else if (this.details.supportTasteIds === "" || !this.details.supportTasteIds) {
        this.$message.error("支持口味不能为空");
      } else if (this.details.styles === "" || !this.details.styles) {
        this.$message.error("款式特点不能为空");
      } else if (this.details.salePrice === "" || !this.details.salePrice) {
        this.$message.error("销售价不能为空");
      } else if (this.details.listImgIds === "" || !this.details.listImgIds) {
        this.$message.error("商品列表图片不能为空");
      } else if (this.details.detailImgIds === "" || !this.details.detailImgIds) {
        this.$message.error("商品详情图片不能为空");
      } else if (this.details.paramImgIds === "" || !this.details.paramImgIds) {
        this.$message.error("商品参数图片不能为空");
      } else if (this.details.securityCodeImg === "" || !this.details.securityCodeImg) {
        this.$message.error("防伪码图片不能为空");
      } else {
        let save = {};
        this.details.goodsSpecInfoIds=this.details.styles
        if (this.details.goodsId) {
          save = await updateGoods(this.details);
        } else {
          this.details.productId = this.$route.query.productId;
          this.details.type = this.$route.query.productType;
          save = await addGoods(this.details);
        }
        if (save.code === 0) {
          this.isSaved = true;
          this.$router.back();
        } else {
          // this.details.images = detailsImg;
        }
      }
    },
    // 重置表单
    handleReset() {
      this.details = this.$options.data().details;
      this.$nextTick(() => {

      });
    },
    // 校验表单是否为空
    validFormIsNull() {
      const form = this.details;
      for (let key in form) {
        if (form.hasOwnProperty(key)) {
          const type = Object.prototype.toString.call(form[key]);
          switch (type) {
            case "[object Array]":
              if (form[key].length) return false;
              break;
            default:
              if (form[key]) return false;
          }
        }
      }
      return true;
    },

    // 返回上一页
    cancelAll() {
      this.$router.back(-1);
    },
    tableChange(e) {
      console.log(e);
    },
    imgupsucss(response, file, fileList, item) {
      // console.log(response, 'p', file, 'w', fileList, 'this', item)
      item.img = this.linsUpimgSucss;
      this.linsUpimgSucss = "";
    },

    // 标签切换页
    tasteCurrentChange (page) {
      this.dicCurrent = page
      const data = {
        current: this.dicCurrent,
        size: this.dicSize,
        label: 'taste'
      }
      this.queryGoodsList(data)
    },

    // 标签切换页
    stylesCurrentChange (page) {
      this.stylesDicCurrent = page
      const data = {
        current: this.stylesDicCurrent,
        size: this.stylesDicSize,
        label: 'product_special'
      }
      this.getDicList(data)
    },

    // 重置分页
    resetPagination () {
      this.dicCurrent = this.dicCurrent
      this.dicSize = this.dicSize
      this.tasteDicTotal = this.tasteDicTotal
      // 店铺标签   店铺产品列表
      this.tasteCurrentChange(1)

    },



    // 重置分页
    resetStylesPagination () {
      this.stylesDicCurrent = this.stylesDicCurrent
      this.stylesDicSize = this.stylesDicSize
      this.stylesDicTotal = this.stylesDicTotal
      // 店铺标签   店铺产品列表
      this.stylesCurrentChange(1)
    },

    // 下拉收起的时候重置下分页
    visibleChange (flag) {
      if (!flag) {
        this.resetPagination()
      }
    },

    visibleStylesChange (flag) {
      if (!flag) {
        this.resetStylesPagination()
      }
    },
  },
};

</script>
<style lang="scss" scoped>
.border {
  overflow: auto;

  ::v-deep .el-input__inner {
    display: inline-block;
    width: 200px;
  }

  ::v-deep .el-upload-list--picture .el-upload-list__item-thumbnail {
    width: 190px;
  }

  .label {
    width: 150px;
    text-align: right;
    line-height: 40px;
  }
}
</style>
 
 